<?php
class Mcache 
{

    static function connect($const_server, $key) 
    {
        $host = &getCacheServer($const_server);
        $host && $host = $host[(hexdec(substr(md5($key),0,4)) % sizeof($host))];
        return $host ? memcache_connect($host['host'], $host['port'], MCACHE_CONNECT_TIMEOUT) : false;
    }

    static function close($conn) 
    {
        memcache_close($conn);
    }

    static function &read($const_server, $key) 
    {
        $ret = null;
        if (is_array($key)) 
        {
            $cache_servers = &getCacheServer($const_server);
            $separated_keys = array();
            foreach ($key as $item) 
            {
                $host_idx = (hexdec(substr(md5($item),0,4)) % sizeof($cache_servers));
                $separated_keys[$host_idx]['ret_keys'][]   = $item;
                $separated_keys[$host_idx]['query_keys'][] = $const_server . '_'. $item;
            }
            $ret = array();
            foreach ($separated_keys as $keys) 
            {
                if ($conn = self::connect($const_server, $keys['ret_keys'][0])) 
                {
                    $rows = memcache_get($conn, $keys['query_keys']);
                    foreach ($keys['ret_keys'] as $idx => $key) 
                    {
                        $ret[$key] = isset($rows[$keys['query_keys'][$idx]]) ? $rows[$keys['query_keys'][$idx]] : false;
                    }
                    self::close($conn);
                }
            }
        }
        else
        {
            if ($conn = self::connect($const_server, $key)) 
            {
                $ret = memcache_get($conn, $const_server.'_'.$key);
                self::close($conn);
            }
        }
        return $ret;
    }

    static function write($const_server, $key, $val, $expire = 0, $flag = 0)
    {
        if ($conn = self::connect($const_server, $key))
        {
            $ret = memcache_set($conn, $const_server.'_'.$key, $val, $flag, $expire);
            self::close($conn);
            return $ret;
        }
    }

    static function delete($const_server, $key, $expire = 0)
    {
        if ($conn = self::connect($const_server, $key))
        {
            $ret = memcache_delete($conn, $const_server.'_'.$key, $expire);
            self::close($conn);
            return $ret;
        }
    }

	static function increment($const_server, $key, $val)
    {
        if ($conn = self::connect($const_server, $key))
        {
            $ret = memcache_increment($conn, $const_server.'_'.$key, $val);
            self::close($conn);
            return $ret;
        }
    }
}

?>